<template>
  <div class="permission-container red-theme">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <div class="batch-actions">
        <el-button type="danger" :disabled="!selectedRoles.length" @click="batchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button type="warning" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
      <div class="right-actions">
        <el-button type="primary" @click="handleCreateRole" :disabled="!canCreate">
          <el-icon><Plus /></el-icon>
          新建角色
        </el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索角色..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon color="#c53030"><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 角色表格 -->
    <el-table
      :data="filteredRoles"
      v-loading="loading"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="角色名称" width="200">
        <template #default="{ row }">
          <div class="role-name">
            <el-icon color="#c53030" style="margin-right: 8px"><User /></el-icon>
            <span>{{ row.name }}</span>
            <el-tag v-if="row.isSystem" type="danger" effect="dark" size="small">
              系统内置
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="权限/成员" width="220">
        <template #default="{ row }">
          <div class="permission-info">
            <el-tag type="danger" size="small">
              <el-icon><Lock /></el-icon>
              {{ row.permissions?.length }} 权限
            </el-tag>
            <el-tag type="warning" size="small" style="margin-left: 8px">
              <el-icon><User /></el-icon>
              {{ row.users?.length }} 成员
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="240" align="center" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button
              type="danger"
              size="small"
              @click="handleEdit(row)"
              :disabled="!canEdit(row)"
              class="action-button"
            >
              <el-icon><Edit /></el-icon>
            </el-button>

            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :disabled="!canDelete(row)"
              class="action-button"
            >
              <el-icon><Delete /></el-icon>
            </el-button>

            <el-dropdown trigger="click">
              <el-button type="danger" size="small" class="action-button">
                <el-icon><More /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="assignUsers(row)">
                    <el-icon><User /></el-icon>分配用户
                  </el-dropdown-item>
                  <el-dropdown-item @click="cloneRole(row)">
                    <el-icon><CopyDocument /></el-icon>克隆角色
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="currentRole.id ? '编辑角色' : '新建角色'"
      width="800px"
      class="red-dialog"
    >
      <el-form :model="currentRole" label-width="100px" ref="roleForm">
        <el-form-item
          label="角色名称"
          prop="name"
          :rules="[
            { required: true, message: '请输入角色名称' },
            { validator: checkRoleName, trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="currentRole.name"
            placeholder="请输入角色名称"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="currentRole.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="权限分配">
          <div class="permission-tree">
            <el-tree
              ref="permissionTree"
              :data="permissions"
              node-key="id"
              show-checkbox
              check-strictly
              :props="treeProps"
              :default-checked-keys="currentRole.permissions"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <el-icon :color="data.isDangerous ? '#c53030' : '#666'">
                    <component :is="data.icon || 'Key'" />
                  </el-icon>
                  <span :style="{ color: data.isDangerous ? '#c53030' : '#333' }">
                    {{ node.label }}
                  </span>
                  <el-tag
                    v-if="data.isDangerous"
                    type="danger"
                    size="small"
                    effect="plain"
                  >
                    高危
                  </el-tag>
                </div>
              </template>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="danger" @click="submitRole">保存角色</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ElTree, ElForm } from 'element-plus'
import {
  Plus, Search, Delete, Edit, More, Lock, User, Download, CopyDocument
} from '@element-plus/icons-vue'


// 类型定义
interface Permission {
  id: string;
  name: string;
  icon?: string;
  isDangerous?: boolean;
  children?: Permission[];
  permissions?: string[];
}

interface Role {
  id?: string;
  name: string;
  description?: string;
  permissions: string[];
  users: string[];
  isSystem?: boolean;
}

// 验证权限数据结构的函数
const validatePermission = (permission: Permission): boolean => {
  if (!permission.id || !permission.name) {
    console.error('权限数据缺少必要字段: id 或 name', permission);
    return false;
  }
  if (permission.children) {
    for (const child of permission.children) {
      if (!validatePermission(child)) {
        return false;
      }
    }
  }
  return true;
};

// 验证角色数据结构的函数
const validateRole = (role: Role): boolean => {
  if (!role.name || !role.permissions) {
    console.error('角色数据缺少必要字段: name 或 permissions', role);
    return false;
  }
  return true;
};

// 权限树数据
const permissions = ref<Permission[]>([
  {
    id: 'sys',
    name: '系统管理',
    icon: 'Setting',
    isDangerous: true,
    children: [
      {
        id: 'user_mgmt',
        name: '用户管理',
        icon: 'User',
        permissions: ['view_users', 'manage_users'],
        children: [
          {
            id: 'user_create',
            name: '创建用户',
            isDangerous: true,
            permissions: ['create_user'],
          },
          {
            id: 'user_edit',
            name: '编辑用户',
            permissions: ['edit_user'],
          },
          {
            id: 'user_delete',
            name: '删除用户',
            isDangerous: true,
            permissions: ['delete_user'],
          },
          {
            id: 'user_activate',
            name: '激活用户',
            permissions: ['activate_user'],
          },
          {
            id: 'user_deactivate',
            name: '停用用户',
            permissions: ['deactivate_user'],
          }
        ]
      },
      {
        id: 'role_mgmt',
        name: '角色管理',
        icon: 'Group',
        permissions: ['view_roles', 'manage_roles'],
        children: [
          {
            id: 'role_create',
            name: '创建角色',
            permissions: ['create_role'],
          },
          {
            id: 'role_edit',
            name: '编辑角色',
            permissions: ['edit_role'],
          },
          {
            id: 'role_delete',
            name: '删除角色',
            isDangerous: true,
            permissions: ['delete_role'],
          }
        ]
      },
      {
        id: 'log_mgmt',
        name: '日志管理',
        icon: 'FileText',
        permissions: ['view_logs', 'clear_logs'],
        children: [
          {
            id: 'login_log',
            name: '登录日志',
            permissions: ['view_login_logs'],
          },
          {
            id: 'operation_log',
            name: '操作日志',
            permissions: ['view_operation_logs'],
          }
        ]
      }
    ],
    permissions: ['sys', 'user_mgmt', 'role_mgmt', 'log_mgmt']
  },
  {
    id: 'content_mgmt',
    name: '内容管理',
    icon: 'File',
    children: [
      {
        id: 'article_mgmt',
        name: '文章管理',
        icon: 'Document',
        permissions: ['view_articles', 'create_articles', 'edit_articles', 'delete_articles'],
        children: [
          {
            id: 'article_publish',
            name: '发布文章',
            permissions: ['publish_article'],
          },
          {
            id: 'article_draft',
            name: '保存草稿',
            permissions: ['save_article_draft'],
          }
        ]
      },
      {
        id: 'image_mgmt',
        name: '图片管理',
        icon: 'Image',
        permissions: ['view_images', 'upload_images', 'delete_images'],
      },
      {
        id: 'video_mgmt',
        name: '视频管理',
        icon: 'Video',
        permissions: ['view_videos', 'upload_videos', 'delete_videos'],
      }
    ],
    permissions: ['content_mgmt', 'article_mgmt', 'image_mgmt', 'video_mgmt']
  },
  {
    id: 'normal_user',
    name: '普通用户',
    icon: 'User',
    permissions: ['view_content', 'comment', 'like', 'share'],
  },
  {
    id: 'developer',
    name: '开发者',
    icon: 'Code',
    permissions: ['view_content', 'edit_code', 'deploy', 'view_code', 'debug'],
  },
  {
    id: 'volunteer',
    name: '志愿者',
    icon: 'Heart',
    permissions: ['view_events', 'participate_events', 'record_volunteer_hours'],
  },
  {
    id: 'government',
    name: '政务部门',
    icon: 'Government',
    permissions: ['view_reports', 'manage_services', 'issue_policies'],
  },
  {
    id: 'missing_person_mgmt',
    name: '失踪人口管理',
    icon: 'User',
    isDangerous: true,
    children: [
      {
        id: 'report_missing',
        name: '报告失踪',
        permissions: ['report_missing_person'],
      },
      {
        id: 'search_missing',
        name: '搜索失踪人口',
        permissions: ['search_missing_person'],
      },
      {
        id: 'update_status',
        name: '更新状态',
        permissions: ['update_missing_person_status'],
      }
    ],
    permissions: ['view_missing_persons', 'manage_missing_persons']
  },
]);

// 验证权限数据
permissions.value.forEach((permission) => {
  validatePermission(permission);
});

// 角色数据
const roles = ref<Role[]>([
  {
    id: 'admin',
    name: '超级管理员',
    description: '拥有系统的最高权限，可进行全面管理',
    permissions: [
      'sys', 'user_mgmt', 'user_create', 'user_edit', 'user_delete', 'user_activate', 'user_deactivate',
      'role_mgmt', 'role_create', 'role_edit', 'role_delete',
      'log_mgmt', 'login_log', 'operation_log',
      'content_mgmt', 'article_mgmt', 'article_publish', 'article_draft', 'image_mgmt', 'video_mgmt',
      'view_content', 'edit_code', 'deploy', 'view_code', 'debug',
      'view_events', 'participate_events', 'record_volunteer_hours',
      'view_reports', 'manage_services', 'issue_policies'
    ],
    users: [],
    isSystem: true
  },
  {
    id: 'content_editor',
    name: '内容编辑',
    description: '负责内容的创建、编辑和发布',
    permissions: [
      'content_mgmt', 'article_mgmt', 'article_publish', 'article_draft', 'image_mgmt', 'video_mgmt'
    ],
    users: [],
  },
  {
    id: 'normal_user',
    name: '普通用户',
    description: '可查看内容、进行评论、点赞和分享',
    permissions: ['view_content', 'comment', 'like', 'share'],
    users: [],
  },
  {
    id: 'developer',
    name: '开发者',
    description: '可进行代码编辑、部署和调试等操作',
    permissions: ['view_content', 'edit_code', 'deploy', 'view_code', 'debug'],
    users: [],
  },
  {
    id: 'volunteer',
    name: '志愿者',
    description: '可查看活动、参与活动并记录志愿时长',
    permissions: ['view_events', 'participate_events', 'record_volunteer_hours'],
    users: [],
  },
  {
    id: 'government',
    name: '政务部门',
    description: '可查看报告、管理服务和发布政策',
    permissions: ['view_reports', 'manage_services', 'issue_policies'],
    users: [],
  },
]);

// 验证角色数据
roles.value.forEach((role) => {
  validateRole(role);
});

// 响应式状态
const loading = ref(false)
const searchKeyword = ref('')
const showDialog = ref(false)
const selectedRoles = ref<Role[]>([])
const currentRole = reactive<Role>({
  name: '',
  description: '',
  permissions: [],
  users: []
})
const permissionTree = ref<InstanceType<typeof ElTree>>()
const roleForm = ref<InstanceType<typeof ElForm>>()

// 权限树配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 权限验证
const currentUser = {
  isAdmin: true
}

const canCreate = computed(() => currentUser.isAdmin)
const canEdit = (role: Role) => !role.isSystem && currentUser.isAdmin
const canDelete = (role: Role) => !role.isSystem && currentUser.isAdmin

// 角色操作方法
const handleCreateRole = () => {
  resetCurrentRole()
  showDialog.value = true
}

const handleEdit = (role: Role) => {
  Object.assign(currentRole, role)
  showDialog.value = true
  nextTick(() => {
    permissionTree.value?.setCheckedKeys(role.permissions)
  })
}

const handleDelete = (role: Role) => {
  ElMessageBox.confirm(`确认删除角色：${role.name}？`, '警告', {
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    roles.value = roles.value.filter(r => r.id !== role.id)
    ElMessage.success('角色删除成功')
  }).catch(() => {
    // 取消删除
  })
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedRoles.value.length} 个角色？`, '警告', {
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    })
    roles.value = roles.value.filter(r => !selectedRoles.value.includes(r))
    selectedRoles.value = []
    ElMessage.success('批量删除成功')
  } catch {}
}

const checkRoleName = (value: string, callback: any) => {
  const isDuplicate = roles.value.some(r => r.name === value && r.id !== currentRole.id)
  isDuplicate ? callback(new Error('角色名称已存在')) : callback()
}

const submitRole = async () => {
  await roleForm.value?.validate()

  const checkedKeys = permissionTree.value?.getCheckedKeys() || []
  if (!checkedKeys.length) {
    return ElMessage.warning('请至少选择一个权限')
  }

  currentRole.permissions = checkedKeys as string[]

  if (currentRole.id) {
    const index = roles.value.findIndex(r => r.id === currentRole.id)
    roles.value.splice(index, 1, { ...currentRole })
  } else {
    roles.value.push({
      ...currentRole,
      id: `role_${Date.now()}`
    })
  }

  showDialog.value = false
  ElMessage.success('角色保存成功')
}

const assignUsers = (role: Role) => {
  ElMessage.info(`进入用户分配流程：${role.name}`)
}

const cloneRole = (role: Role) => {
  const cloned = { ...role, id: `clone_${Date.now()}`, name: `${role.name}_副本` }
  roles.value.push(cloned)
  ElMessage.success('角色克隆成功')
}

// 辅助方法
const resetCurrentRole = () => {
  currentRole.id = undefined
  currentRole.name = ''
  currentRole.description = ''
  currentRole.permissions = []
  currentRole.users = []
}

const filteredRoles = computed(() => {
  const keyword = searchKeyword.value.toLowerCase()
  return roles.value.filter(role =>
    role.name.toLowerCase().includes(keyword) ||
    role.description?.toLowerCase().includes(keyword)
  )
})

const handleSelectionChange = (val: Role[]) => {
  selectedRoles.value = val
}

const exportData = () => {
  ElMessage.success('导出成功（模拟）')
}
</script>

<style lang="scss">
.red-theme {
  // 覆盖Element Plus红色主题
  --el-color-primary: #c53030;
  --el-color-primary-light-3: #d66060;
  --el-color-primary-dark-2: #a32424;
  --el-button-active-border-color: var(--el-color-primary);

  .el-button--danger {
    --el-button-hover-bg-color: #a32424;
    --el-button-active-bg-color: #8a1f1f;
  }

  .el-tag--danger {
    --el-tag-bg-color: #fef0f0;
    --el-tag-border-color: #fcd3d3;
    --el-tag-text-color: #d66060;
  }

  .el-table {
    --el-table-border-color: #f0d4d4;
    --el-table-header-bg-color: #fce8e8;
    th.el-table__cell {
      background-color: var(--el-table-cell-bg-color);
    }
  }

  .el-dialog.red-dialog {
    .el-dialog__header {
      border-bottom: 1px solid #f0d4d4;
      .el-dialog__title {
        color: #c53030;
      }
    }
  }
}

.permission-container {
  padding: 20px;
  border-radius: 8px;

  .operation-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 12px;
    background: var(--detail-section-background);
    border-radius: 8px;

    .batch-actions {
      display: flex;
      gap: 12px;
    }

    .right-actions {
      display: flex;
      gap: 12px;
    }
  }

  .role-name {
    display: flex;
    align-items: center;
  }

  .permission-tree {
    border: 1px solid #f0d4d4;
    border-radius: 4px;
    padding: 12px;
    max-height: 400px;
    overflow-y: auto;

    .tree-node {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 6px 0;

      .el-icon {
        font-size: 16px;
      }
    }
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(198, 48, 48, 0.1);

    .el-tag {
      border-radius: 12px;
      padding: 0 10px;
      height: 24px;
    }

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin: 0;
    }

    .action-button {
      padding: 8px 8px; /* 统一按钮内边距，调整按钮大小 */
      min-width: 32px; /* 设置最小宽度，统一按钮宽度 */
      height: 32px; /* 设置高度，统一按钮高度 */
      border-radius: 4px; /* 统一按钮圆角 */
      margin: 0;
    }
  }
}
</style>
